package com.lagou.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
@Service
public class FileUpLoadService {
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient  ossClient;
    // 允许上传的格式
//    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
//            ".jpeg", ".gif", ".png"};
    private static final String[] IMAGE_TYPE = new String[]{".jpg", ".jpeg",".png"};

    private static final long MAX_FILE_SIZE = 5*1024*1024L;
    public UpLoadResult  upload(MultipartFile multipartFile){
        // 校验图片格式
        boolean  isLegal = false;
        for (String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        UpLoadResult upLoadResult = new UpLoadResult();
        if (!isLegal){
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("图片格式不符");
            return  upLoadResult;
        }
        if (multipartFile.getSize() > MAX_FILE_SIZE) {
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("文件大小超过限制");
            return  upLoadResult;
        }
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return  upLoadResult;
        }
        upLoadResult.setStatus("done");
//        https://lagou-oss-test.oss-cn-beijing.aliyuncs.com/images/2020/08/16/46208c5d-d5d9-4a8b-9938-ab0b7f2a90fc.png
        upLoadResult.setName("https://"+aliyunConfig.getBucketName()+"."+aliyunConfig.getEndpoint()+"/"+filePath);
        upLoadResult.setUid(filePath);
        return  upLoadResult;
    }

    public void downloadFile(String uid, OutputStream outputStream) throws IOException{
        OSSObject ossObject = ossClient.getObject(new GetObjectRequest(aliyunConfig.getBucketName(), uid));
        byte[] buffer = new byte[8192];
        try (InputStream objectContent = ossObject.getObjectContent();
             OutputStream out = outputStream){
            int bytesRead;
            while((bytesRead = objectContent.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }

    public void deleteFile(String uid){
        ossClient.deleteObject(new GetObjectRequest(aliyunConfig.getBucketName(), uid));
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
